package com.application.api;

import com.application.module.couponused.CouponUsedService;
import com.application.module.course.Course;
import com.application.module.course.CourseService;
import com.application.module.courseitem.CourseItem;
import com.application.module.coursezan.CourseZan;
import com.application.module.favorite.Favorite;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Record;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;

import java.util.List;


/**
 */
@Controller("/api/course")
public class CourseApiController extends BaseController {

    @SuppressWarnings("unused")
    private static final Log log = Log.getLog(CourseApiController.class);

    CouponUsedService couponUsedService;
    CourseService courseService;

    /**
     * 列表
     */
    public void index() {
        String cid = getPara("categoryId");
        int uid = getCUserId();
        /*if (StrKit.isBlank(cid)) {
            error(400, "请输入课程分类");
            return;
        }*/
        splitPage.getQueryParam().put("categoryId", cid);
        splitPage.getQueryParam().put("course_name", getPara("keyword"));
        paging(splitPage, "app.course.listSelect", "app.course.listFrom");
        List<Record> list = (List<Record>) splitPage.getList();
        list.forEach(o -> {
            int courseId = o.getInt("id");
            int num = CourseZan.dao.findCourseZans(courseId);
            int unlocks = couponUsedService.getUnlockCourseItemNum(uid, courseId);
            int items = CourseItem.dao.findCount(courseId);
            o.set("zans", num).set("unlocks", unlocks).set("items", items);
        });

        //获取课时列表
        List<CourseItem> items = CourseItem.dao.findByCatId(cid);
        splitPage.setExtData(items);

        success(splitPage);
    }


    /**
     * 课程详情，是否收藏、购买、点赞等
     */
    public void view() {
        Course course = courseService.getView(getParaToInt(), getCUserId());
        success(course);
    }

    /*
    收藏课程或取消课程api/course/favorite/{courseId}
     */
    public void favorite() {
        int r = Favorite.dao.addOrDel(getParaToInt(), getCUserId());
        success(r, r > 0 ? "收藏成功" : "取消收藏");
    }

    /*
    课程点赞
     */
    public void zan() {
        int r = CourseZan.dao.addOrDel(getParaToInt(), getParaToInt("itemId"), getCUserId());
        success(r, r > 0 ? "成功" : "取消点赞");
    }
}
